<template>
	<view class="container">
		<form @submit="formSubmit" @reset="formReset">
			<view class="sub-title">房屋信息</view>
			<tui-list-cell :arrow="true" class="tui-list">

				<text class="tui-list-cell-name required">房屋</text>
				<view class="tui-right">
					<picker @change="bindPickerChange" :range="roomCloums" data-key="homeIndex">
						<view class="uni-input">{{roomCloums[homeIndex] || '请选择房屋'}}</view>
					</picker>
				</view>
			</tui-list-cell>
			<view class="sub-title">报修信息</view>
			<tui-list-cell :hover="false" :arrow="true">
				<view class="tui-line-cell">
					<view class="tui-list-cell-name required">报修类型</view>
					<view class="tui-right">
						<picker @change="bindPickerChange" :value="index" :range="columns" data-key="typeIndex">
							<view class="uni-input">{{columns[typeIndex] || '请选择报修类型'}}</view>
						</picker>
					</view>
				</view>
			</tui-list-cell>
			<tui-list-cell>
				<view class="tui-line-cell">
					<view class="tui-list-cell-name required">
						报修人
					</view>
					<input placeholder-class="tui-phcolor" 
					:value="userInfo.userName"
					class="tui-input" name="bindRepairName" placeholder="请输入报修人" maxlength="50"
					 type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell>
				<view class="tui-line-cell">
					<view class="tui-list-cell-name required">
						手机号
					</view>
					<input 
					:value="userInfo.link"
					placeholder-class="tui-phcolor" 
					class="tui-input" name="bindTel" 
					placeholder="请输入手机号" 
					maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false" :arrow="true">
				<view class="tui-line-cell">
					<view class="tui-title required">预约上门时间</view>
					<view class="tui-right">
						<view class="uni-input" @click="show">{{time}}</view>
					</view>
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-title tui-top40 required">问题描述框</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">

				<view class="tui-cells">
					<textarea class="tui-textarea" name="context" v-model="context" placeholder="请详细描述您的问题,上传图片便于我们更好的解决问题" maxlength="500"
					 placeholder-class="tui-phcolor-color" />
					<view class="tui-textarea-counter">{{context.length}}/500</view>
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false" ><view class="tui-title tui-top40">图片上传（请点击加号上传）</view></tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-box-upload">
					<tui-upload 
					:serverUrl="serverUrl" 
					@complete="result" 
					@remove="remove"></tui-upload>
				</view>
			</tui-list-cell>
			<view class="tui-btn-box">
				<tui-button class="tui-btn tui-danger tui-fillet" hover-class="tui-danger-hover" formType="submit">提 交</tui-button>
			</view>
		</form>
		<tui-datetime ref="dateTime" :type="type" :startYear="startYear" :endYear="endYear" :cancelColor="cancelColor" :color="color"
		 :setDateTime="setDateTime" @confirm="change"></tui-datetime>
	</view>
</template>
<script>
	import tuiDatetime from "@/components/dateTime/dateTime"
	const form = require("../../components/utils/formValidation.js")
	import tuiListCell from "@/components/list-cell/list-cell"
	import tuiButton from "@/components/button/button"
	import utils from "@/utils/util.js"
	export default {
		components: {
			tuiListCell,
			tuiDatetime,
			tuiButton
		},
		
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				serverUrl:'',
				type: 1,
				startYear: 1980,
				endYear: 2030,
				cancelColor: "#888",
				color: "#5677fc",
				setDateTime: "",
				title: 'picker',
				context:'',
				arrayF:[{
						name:'恒大',
						val:1
					}, {
						name:'万科',
						val:2,
				}],
				homeIndex:'',
				typeIndex:'',
				roomCloums:[],
				roomIdArr:[],
				imgList:[],
				userId:'',
				communityId:'',
				array: ['中国', '美国', '巴西', '日本'],
				columns: ['卧室报修', '管道报修', '客厅报修'],
				index: 0,
				date: currentDate,
				time: '请选择上门时间'
			}
		},
		computed: {
				startDate() {
						return this.getDate('start');
				},
				endDate() {
						return this.getDate('end');
				},
				userInfo(){
					let us = {}
					try{
						us = uni.getStorageSync(this.java110Constant.mapping.USER_INFO);
						us = this.java110Util.des.desDecrypt(us)
						us = JSON.parse(us)
					}catch(e){
						//TODO handle the exception
					}
					return us
				}
		},
		mounted() {
			let that = this;
			uni.showLoading({
				mask: true,
				title: '请稍候...'
			})
			this.java110Context.getRooms().then(res=>{
			  let arr = res.data.rooms;
			  let roomCloums = [];
			  let roomIdArr = [];
			  arr.map(item => {
				roomCloums.push(item.floorNum + "号楼" + item.unitNum + "单元" + item.roomNum + "室");
				roomIdArr.push(item.roomId);
			  })
			  that.roomCloums = roomCloums;
			  that.roomIdArr = roomIdArr;
			  that.userId = res.data.owner.appUserId;
			  that.communityId = res.data.owner.communityId;
			  uni.hideLoading();
			})
		},
		methods: {
			result:async function(org){
				if(org.status === 1){
					let resList = [];
					let imgList = org.imgArr.forEach(async item => {
						this.java110Factory.base64.urlTobase64(item).then(res => {
							resList.push(res)
							this.imgList = [...resList]; 
						});
					});
					
				}
			},
			remove:function(index){
				this.imgList.splice(index, 1);
			},
			onNavigationBarButtonTap(data) {
				uni.navigateTo({
					url:'./infolist/infolist?' + utils.param(this.pageData) 
				})
			},
			show: function(type) {
				this.cancelColor = "#888";
				this.color = "#5677fc";
				this.setDateTime = "";
				this.startYear = 1980;
				this.endYear = 2030;
				this.$refs.dateTime.show()
			},
			change: function(e) {
				console.log(e)
				this.time = e.result
			},
			formSubmit: function(e) {
				//表单规则
				let rules = [{
					name: "bindRepairName",
					rule: ["required", "isChinese", "minLength:2", "maxLength:6"], //可使用区间，此处主要测试功能
					msg: ["请输入姓名", "姓名必须全部为中文", "姓名必须2个或以上字符", "姓名不能超过6个字符"]
				},{
					name: "bindTel",
					rule: ["required", "isMobile"],
					msg: ["请输入手机号", "请输入正确的手机号"]
				},
				{
					name: "context",
					rule: ["required", "maxLength:500"],
					msg: ["请输入问题描述", "问题描述最多不能超过500字"]
				}
				];
				//进行表单检查
				let formData = e.detail.value;
				if( this.homeIndex !== 0 && !this.homeIndex){
					this.tui.toast('请选择房屋')
					return
				}
				if( this.typeIndex !== 0 && !this.typeIndex){
					this.tui.toast('请选择保修类型')
					return
				}
				if(!this.time || this.time === '请选择上门时间'){
					this.tui.toast('请选择预约上门时间')
					return
				}
				let checkRes = form.validation(formData, rules);
				if (!checkRes) {
					let obj = {
					  "repairName": formData.bindRepairName,
					  "repairType": this.typeIndex?'809001' : '809002',
					  "appointmentTime": this.time + ":00",
					  "tel": formData.bindTel,
					  "roomId": this.roomIdArr[this.homeIndex],
					  "photos": this.imgList,
					  "context": formData.context,
					  "userId": this.userId,
					  "communityId": this.communityId,
					  "bindDate": this.time.split(' ')[0],
					  "bindTime": this.time.split(' ')[1]
					}
					uni.showLoading({
						mask: true,
						title: '请稍候...'
					})
					this.java110Context.request({
					        url: this.java110Constant.url.saveOwnerRepair, //  http://hc.demo.winqi.cn:8012/appApi/ownerRepair.saveOwnerRepair 
					        header: this.java110Context.getHeaders(),
					        method: "POST",
					        data:obj, //动态数据
					        success: function(res) {
							  uni.hideLoading();
					          if (res.statusCode == 200) {
					            uni.redirectTo({
					              url: '/pages/drawer/infolist/infolist',
					            });
					            return;
					          }
					          uni.showToast({
					            title: "服务器异常了",
					            icon: 'none',
					            duration: 2000
					          })
					        },
					        fail:function(e){
							  uni.hideLoading();
					          uni.showToast({
					            title: "服务器异常了",
					            icon: 'none',
					            duration: 2000
					          })
					        }
					      });

				} else {
					uni.showToast({
						title: checkRes,
						icon: "none"
					});
				}
			},
			
			bindPickerChange: function(e) {
				let { key } = e.target.dataset;
				this[key] = e.target.value
			},
			bindDateChange: function(e) {
					this.date = e.target.value
			},
			bindTimeChange: function(e) {
					this.time = e.target.value
			},
			getDate(type) {
					const date = new Date();
					let year = date.getFullYear();
					let month = date.getMonth() + 1;
					let day = date.getDate();

					if (type === 'start') {
							year = year - 60;
					} else if (type === 'end') {
							year = year + 2;
					}
					month = month > 9 ? month : '0' + month;;
					day = day > 9 ? day : '0' + day;
					return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style>
	.container {
		padding: 20rpx 0 50rpx 0;
	}

	.tui-line-cell {
		width: 100%;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}

	.tui-title {
		line-height: 32rpx;
		flex-shrink: 0;
	}
	.tui-right {
		margin-left: auto;
		margin-right: 34upx;
		font-size: 26upx;
		line-height: 1;
		color: #999;
	}
	.tui-input {
		font-size: 32rpx;
		color: #333;
		flex: 1;
		text-align: right;
	}
	.picker-lable{
		padding-left: 20rpx;
	}
	.radio-group {
		margin-left: auto;
		transform: scale(0.8);
		transform-origin: 100% center;
		flex-shrink: 0;
	}

	.tui-radio {
		display: inline-block;
		padding-left: 28rpx;
		font-size: 36rpx;
		vertical-align: middle;
	}


	.tui-btn-box {
		padding: 40rpx 50rpx;
		box-sizing: border-box;
	}

	.btn-gray {
		margin-top: 30rpx;
	}

	.tui-tips {
		padding: 30rpx;
		color: #999;
		font-size: 24rpx;
	}
	.btn-primary{
		background: #e41f19;
	}
	uni-textarea{
		width: 700rpx;
	}
</style>
